package com.startit.csv;

import com.startit.csv.exception.TokenException;


public class Tokenizer {
	private String str;
	private char d = ',';
	private char q = '"';
	private int currPos = 0;
	private int lastPos = -1;
	private int len = 0;
	private char currD;

	public Tokenizer(String str) {
		this.str = str;
		this.len = this.str.length();
	}

	public Tokenizer(String str, char delim, char quote) throws TokenException {
		this(str);
		if (delim==quote)
			throw new TokenException("Delimeter and quote must be different.");
		this.d = delim;
		this.q = quote;
		this.currD = this.d;
	}
	
	private int skip(char c, int startPos){
		currD = c;
		lastPos++;
		return skipDelimeter(++startPos);
	}

	private int skipDelimeter(int startPos) {
		int indexOfD = str.indexOf(currD, startPos);
		if (str.charAt(startPos)==q && currD != q) {
			return skip(q, startPos);
		} else if (str.charAt(startPos)==d && currD != d) {
			return skip(d, startPos);
		}
		return indexOfD > 0 ? indexOfD : len;
	}

	public String nextToken() {
		if (currPos>len)
			return null;
		int newPos = skipDelimeter(currPos);
		String str = this.str.substring(lastPos+1, newPos);
		lastPos = newPos;
		currPos = newPos+1;
		return str;
	}

}
